package com.networklib;

import android.os.Environment;

import com.networklib.task.TaskResultCode;
import com.networklib.task.reflect.TypeToken;
import com.networklib.task.exception.TaskException;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

import okhttp3.Response;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * Created by ASUS on 2017/6/13.
 */

public class TaskResult {
    private final String tag;
    private TaskResultCode resultCode;
    private Object result;

    public TaskResult(String tag, TaskResultCode success) {
        this.tag = tag;
    }

    public void setResultCode(TaskResultCode resultCode) {
        this.resultCode = resultCode;
    }

    public TaskResultCode getResultCode() {
        return resultCode;
    }

    public String getTag() {
        return tag;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public Object getResult() {
        return result;
    }


    public <T> T getResult(TypeToken<T> typeToken) throws TaskException, IOException {
        if(this.result == null) {
            return null;
        } else if(typeToken == null) {
            throw new TaskException("给出的类型为NULL  <>  typeToken=NULL");
        }  else {
            Class aClass = typeToken.getRawType();
            if(aClass.isInstance(String.class)) {
                return (T) ((Response)this.getResult()).body().string();
            }else if(aClass.isInstance(File.class)){
                Response response = ((Response) this.getResult());
                File file = new File(Environment.DIRECTORY_DOWNLOADS, System.currentTimeMillis()+"");
                BufferedSink bufferedSink = Okio.buffer(Okio.sink(file));
                BufferedSource bufferedSource = response.body().source();
                bufferedSink.writeAll(bufferedSource);
                bufferedSink.flush();
                bufferedSink.close();
                bufferedSource.close();
                return (T) file;
            } else {
                throw new TaskException(MessageFormat.format("给出的类型不正确 typeToken is < {0} > result is < {1} >", new Object[]{aClass.toString(), this.result.getClass().toString()}));
            }
        }
    }
}
